package cn.edu.ctbu.dp07.controller;

import cn.edu.ctbu.dp07.entity.Student;
import cn.edu.ctbu.dp07.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private StudentService studentService;

    /**
     * 显示学生列表页面
     */
    @GetMapping("/list")
    public String list(Model model) {
        List<Student> students = studentService.findAll();
        model.addAttribute("students", students);
        return "student/list";
    }

    /**
     * 显示添加学生页面
     */
    @GetMapping("/add")
    public String add(Model model) {
        model.addAttribute("student", new Student());
        return "student/edit";
    }

    /**
     * 显示编辑学生页面
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable Integer id, Model model) {
        Student student = studentService.findById(id);
        model.addAttribute("student", student);
        return "student/edit";
    }

    /**
     * 保存学生信息
     */
    @PostMapping("/save")
    public String save(Student student) {
        studentService.save(student);
        return "redirect:/student/list";
    }

    /**
     * 删除学生
     */
    @GetMapping("/delete/{id}")
    public String delete(@PathVariable Integer id) {
        studentService.deleteById(id);
        return "redirect:/student/list";
    }
    
    /**
     * 根据学号或姓名查询学生
     */
    @GetMapping("/search")
    public String search(@RequestParam(required = false) String keyword, Model model) {
        List<Student> students;
        if (keyword != null && !keyword.isEmpty()) {
            students = (List<Student>) studentService.findByNameContaining(keyword);
        } else {
            students = studentService.findAll();
        }
        model.addAttribute("students", students);
        model.addAttribute("keyword", keyword);
        return "student/list";
    }
}